/*
 * File Name：ActFinishHandler.java
 * Copyright：Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description： ActFinishHandler.java
 * Modify By：res-jxliu
 * Modify Date：2015年3月21日
 * Modify Type：Add
 */
package com.ciwong.mobilelib.utils;

import java.lang.reflect.Field;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;

import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.mobilelib.R;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.ui.BaseActivityGroup;
import com.ciwong.mobilelib.widget.RootViewGroup;
import com.ciwong.mobilelib.widget.RootViewGroup.RootViewGroupAnimationListener;

/**
 * 关闭Activity处理器
 * 
 * @author res-jxliu
 * @version ciwong v.1.0 2015年3月21日
 * @since ciwong v.1.0
 */
public class ActFinishHandler implements OnTouchListener,
        RootViewGroupAnimationListener
{

    private static final int MIN_X_DISTANCE;

    private static final int MAX_Y_DISTANCE;

    private int MAX_LEFT_DISTANCE;

    private RootViewGroup rootView;

    private Activity mActivity;

    // 记录手指按下时的横坐标。
    private float xDown;

    // 记录手指移动时的横坐标。
    private float xMove;

    private float yDown;

    private float xDistance;

    private float yDistance;

    // 用于计算手指滑动的速度。
    private VelocityTracker mVelocityTracker;

    private int screenWidth;

    // private int screenHeight;

    // private ViewGroup mContentView;

    // private int MAX_TRANSLATE = 33;

    private RootViewGroup mLowerRootView;

    private View mShadowView;

    private static int LOWER_ROOTVIEW_MARGINRIGHT;

    // private List<View> childViewList = new ArrayList<View>();

    private float mPercent = 1.0f;

    private boolean IS_FIRST_LOAD = false;

    /**
     * 设置上层rootview是否可以跟随手指移动
     */
    // private boolean CAN_MOVE = true;

    // /**
    // * 判断当前触点是否在受冲突的VIEW区域之内
    // */
    // private boolean MOVE_FORBID = false;

    /**
     * 设置底层控件是否可以长按
     */
    private boolean IS_LONG_CLICK_ABLE = true;

    // private boolean IS_TRANSFER = false;

    /**
     * 原始关闭状态
     */
    private final int STATU_ORG = 0;

    /**
     * view移动中，手未放开
     */
    private final int STATU_TRANSFER = 1;

    /**
     * view移动中，手已经放开
     */
    private final int STATU_MOVING = 2;

    /**
     * 当前状态
     */
    private int STATU_CURRENT = STATU_ORG;

    public static final int SHADOW_WIDTH;

    private static final int MOVE_TIME_WHOLE = 600;

    private static final int MOVE_TIME = 300;

    static
    {
        MIN_X_DISTANCE = DeviceUtils.dip2px(20);
        LOWER_ROOTVIEW_MARGINRIGHT = DeviceUtils.dip2px(200);
        MAX_Y_DISTANCE = DeviceUtils.dip2px(30);
        SHADOW_WIDTH = DeviceUtils.dip2px(10);
    }

    public ActFinishHandler(final Activity act)
    {
        mActivity = act;
        screenWidth = DeviceUtils.getScreenWdith();
        MAX_LEFT_DISTANCE = screenWidth;
        // screenHeight = DeviceUtils.getScreenHeight();
//        mShadowView = act.findViewById(R.id.shadow_view);
        this.rootView = (RootViewGroup) (((ViewGroup) act
                .findViewById(android.R.id.content)).getChildAt(0));
        rootView.setOnTouchListener(this);
        rootView.setRootViewGroupAnimationListener(this);
        // mContentView = (ViewGroup) act.findViewById(android.R.id.content);
        // mContentView.setBackgroundColor(Color.parseColor("#" + MAX_TRANSLATE
        // + "000000"));

        initLowerRootView(act);

        STATU_CURRENT = STATU_MOVING;
        // rootView.scrollToStart(600);
        rootView.scrollToStart(MOVE_TIME_WHOLE);
        IS_FIRST_LOAD = true;
    }

    private boolean isHandle;

    public boolean dispatcheOntouchEvent(MotionEvent ev)
    {
        switch (ev.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                isHandle = false;
                if (ev.getX() > MAX_LEFT_DISTANCE)
                {
                    return false;
                }
                else
                {
                    isHandle = true;
                }
        }
        if (isHandle)
        {
            return onTouch(rootView, ev);
        }
        return false;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        if (mActivityCanMoveHandler != null
                && !mActivityCanMoveHandler.canMove())
        {
            return false;
        }
        if (STATU_CURRENT == STATU_MOVING)
        {
            return true;
        }
        createVelocityTracker(event);
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                xDown = event.getRawX();
                yDown = event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                cancelLongClick();
                xMove = event.getRawX() - xDown;
                xDistance = event.getX() - xDown;
                mPercent = 1 - xMove / screenWidth;
                yDistance = event.getRawY() - yDown;
                // 活动的距离
                // 获取顺时速度
                // System.out.println("xDown=" + xDown + "xDistance="
                // + (event.getX() - xDown) + "yDistance="
                // + (event.getRawY() - yDown));

                if (xMove < 0)
                {
                    xMove = 0;
                }
                if (((Math.abs(yDistance) <= MAX_Y_DISTANCE) && (xDistance > MIN_X_DISTANCE))
                        || STATU_CURRENT == STATU_TRANSFER)
                {
                    Log.i("act", xMove + "-------------------" + STATU_CURRENT);
                    STATU_CURRENT = STATU_TRANSFER;
                    transferView();
                    setBackGroundColor();
                    // if (STATU_CURRENT=STATU_TRANSFER && IS_FIRST_TRANSFER
                    // && mListener != null)
                    // {
                    // IS_FIRST_TRANSFER = false;
                    // mListener.activityAnimationFirstOpen();
                    // }
                }
                break;
            case MotionEvent.ACTION_UP:
                // if (MOVE_FORBID)
                // {
                // return false;
                // }
                IS_LONG_CLICK_ABLE = true;
                if (STATU_CURRENT == STATU_TRANSFER)
                {

                    STATU_CURRENT = STATU_MOVING;
                    rootView.scrollToEnd(mVelocityTracker, false, MOVE_TIME);
                }
                recycleVelocityTracker();
                if (rootView.getScrollX() < 0)
                {
                    event.setAction(MotionEvent.ACTION_CANCEL);
                    return false;
                }
                break;
            default:
                break;
        }
        if (rootView.getScrollX() < 0)
        {
            return true;
        }
        return false;
    }

    private void transferView()
    {
        rootView.scrollTo((int) -xMove, 0);
        if (mLowerRootView == null)
        {
            return;
        }
        mLowerRootView.scrollTo((int) (LOWER_ROOTVIEW_MARGINRIGHT * mPercent),
                0);
    }

    /**
     * 创建VelocityTracker对象，并将触摸content界面的滑动事件加入到VelocityTracker当中。
     * 
     * @param event
     * 
     */
    private void createVelocityTracker(MotionEvent event)
    {
        if (mVelocityTracker == null)
        {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(event);
    }

    /**
     * 回收VelocityTracker对象。
     */
    private void recycleVelocityTracker()
    {
        mVelocityTracker.recycle();
        mVelocityTracker = null;
    }

    private void setBackGroundColor()
    {
        if (mShadowView != null)
        {
            mShadowView.setAlpha(mPercent);
        }
    }

    // @Override
    // public void finish()
    // {
    // finishEverything();
    // }

    @Override
    public void reBack()
    {
        STATU_CURRENT = STATU_ORG;
        Log.i("mLowerRootView", LOWER_ROOTVIEW_MARGINRIGHT * mPercent
                + "reBack");
        if (mLowerRootView != null)
        {
            mLowerRootView.scrollTo(LOWER_ROOTVIEW_MARGINRIGHT, 0);
        }
        if (mListener == null)
        {
            return;
        }

        if (IS_FIRST_LOAD)
        {
            IS_FIRST_LOAD = false;
            mListener.activityAnimationComplete();
        }
        else
        {
//            mListener.activityAnimationReBack();
        }
    }

    @Override
    public void moving(boolean isFinish, int X, int Y)
    {
        if (X < -screenWidth)
        {
            finishEverything();
        }
        mPercent = 1.0f + 1.1f * X / screenWidth;
        setBackGroundColor();
        if (mLowerRootView != null)
        {
            int destictionX = (int) (LOWER_ROOTVIEW_MARGINRIGHT * mPercent);
            if (destictionX < 0)
            {
                mLowerRootView.scrollTo(0, 0);
            }
            else
            {
                mLowerRootView.scrollTo(destictionX, 0);
            }
        }
    }

    public void initLowerRootView(Activity act)
    {
        Activity activity = BaseActivityManager.getInstance().getLowerActivity(
                act);
        if (activity != null)
        {
            Log.i("se7en", activity.toString());
            mLowerRootView = (RootViewGroup) (((ViewGroup) activity
                    .findViewById(android.R.id.content)).getChildAt(0));
        }
    }

    private void finishEverything()
    {
        Log.i("mLowerRootView", LOWER_ROOTVIEW_MARGINRIGHT * mPercent
                + "finish");
        if (mLowerRootView != null)
        {
            mLowerRootView.scrollTo(0, 0);
        }
        if (mListener != null)
        {
            mListener.activityAnimationFinish();
        }
        if (mActivity instanceof BaseActivity)
        {
            mActivity.finish();
        }
        else if (mActivity instanceof BaseActivityGroup)
        {
            ((BaseActivityGroup) mActivity).finishActivity();
        }
    }

    public void finishActivity()
    {
        STATU_CURRENT = STATU_MOVING;
        rootView.scrollToEnd(mVelocityTracker, true, 300);
    }

    public void setLeftTouchAbleWidth(int width)
    {
        this.MAX_LEFT_DISTANCE = width;
    }

    /**
     * 向右滑动activity再回到当前页面的回调
     * 
     * @author res-jianpingliu
     * 
     */
    public interface ActivityAnimationEndListener
    {
        /**
         * 
         * activity初次加载动画结束回调方法
         * 
         */
        void activityAnimationComplete();

        /**
         * 回来的动画结束后的回调方法
         */
        void activityAnimationReBack();

        /**
         * activity被关闭，动画结束回调方法
         */
        void activityAnimationFinish();

        /**
         * activity首次调用Move
         */
        void activityAnimationFirstOpen();

    }

    private ActivityAnimationEndListener mListener;

    public void setActivityAnimationEndListener(
            ActivityAnimationEndListener listener)
    {
        mListener = listener;
    }

    public RootViewGroup getmLowerRootView()
    {
        return mLowerRootView;
    }

    public void setmLowerRootView(RootViewGroup mLowerRootView)
    {
        this.mLowerRootView = mLowerRootView;
    }

    private void cancelLongClick()
    {
        if (STATU_CURRENT == STATU_ORG || !IS_LONG_CLICK_ABLE)
        {
            return;
        }
        MessageQueue msgQueue = Looper.myQueue();
        if (msgQueue == null)
        {
            return;
        }
        Message msg = (Message) getPrivateObject(msgQueue, "mMessages");
        if (msg == null)
        {
            return;
        }
        Runnable runnable = (Runnable) getPrivateObject(msg, "callback");
        if (runnable == null)
        {
            return;
        }
        String clzName = runnable.getClass().getName();
        if (clzName != null
                && "android.view.View$CheckForLongPress".equals(clzName))
        {
            Handler handler = (Handler) getPrivateObject(msg, "target");
            if (handler == null)
            {
                return;
            }
            handler.removeCallbacks(runnable);
            IS_LONG_CLICK_ABLE = false;
            Log.i("base", "handler.removeCallbacks(runnable);");
        }
    }

    private Object getPrivateObject(Object obj, String name)
    {
        try
        {
            Class<?> clz = obj.getClass();
            Field field;
            field = clz.getDeclaredField(name);
            field.setAccessible(true); // 抑制Java对修饰符的检查
            return field.get(obj);
        }
        catch (Exception e)
        {
            return null;
        }
    }

    public interface ActivityCanMoveHandler
    {
        boolean canMove();
    }

    ActivityCanMoveHandler mActivityCanMoveHandler;

    public void setActivityCanMoveHandler(
            ActivityCanMoveHandler activityCanMoveHandler)
    {
        this.mActivityCanMoveHandler = activityCanMoveHandler;
    }

}
